from fastapi import APIRouter, Depends, HTTPException, status
from src.schemas.detection import (
    DetectionHistoryRequest,
    DetectionHistoryResponse,
    StepDetectionRequest,
    StepDetectionResponse,
    FinalSummaryRequest,
    FinalSummaryResponse,
    StepDetectionApiResponse,
    FinalSummaryApiResponse
)
from src.schemas import SuccessResponse, ErrorResponse
from src.services import DetectionService
from src.utils.auth import get_current_user
from src.models import User
from src.utils.logger import app_logger as logger
# 移除 InvalidImageException 导入，因为不再使用

router = APIRouter(prefix="/detection")




@router.get(
    "/history",
    response_model=SuccessResponse[DetectionHistoryResponse],
    summary="获取检测历史",
    description="获取用户的检测历史记录，支持分页查询"
)
async def get_detection_history(
    page: int = 1,
    limit: int = 10,
    current_user: User = Depends(get_current_user)
):
    """获取检测历史"""
    try:
        # 验证分页参数
        if page < 1:
            page = 1
        if limit < 1 or limit > 50:
            limit = 10
        
        result = await DetectionService.get_detection_history(
            current_user.id,
            page,
            limit
        )
        return SuccessResponse(
            data=result,
            message="获取检测历史成功"
        )
    except Exception as e:
        logger.error(f"获取检测历史失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取检测历史失败: {str(e)}"
        )


@router.get(
    "/record/{record_id}",
    response_model=SuccessResponse[dict],
    summary="获取检测记录详情",
    description="根据记录ID获取检测记录的详细信息"
)
async def get_detection_record(
    record_id: int,
    current_user: User = Depends(get_current_user)
):
    """获取检测记录详情"""
    try:
        result = await DetectionService.get_detection_record(
            current_user.id,
            record_id
        )
        return SuccessResponse(
            data=result,
            message="获取检测记录成功"
        )
    except Exception as e:
        error_msg = str(e)
        logger.error(f"获取检测记录失败: {error_msg}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取检测记录失败: {error_msg}"
        )


@router.post(
    "/step-detection",
    response_model=StepDetectionApiResponse,
    summary="分步检测 - 单张图片检测",
    description="分步进行AI检测，每次检测一张图片并返回结果，支持实时反馈"
)
async def step_detection(
    request: StepDetectionRequest,
    current_user: User = Depends(get_current_user)
):
    """分步检测 - 单张图片检测"""
    try:
        # 创建检测服务实例
        detection_service = DetectionService()
        
        # 转换图片信息格式
        image_info = {
            'imageUrl': request.image_info.image_url,
            'angle': request.image_info.angle,
            'ossPath': request.image_info.oss_path
        }
        
        result = await detection_service.step_detection(
            user_id=current_user.id,
            session_id=request.session_id,
            image_info=image_info
        )
        
        return SuccessResponse(
            data=result,
            message=f"第{result.step}步检测完成"
        )
        
    except Exception as e:
        error_msg = str(e)
        logger.error(f"分步检测失败: {error_msg}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"分步检测失败: {error_msg}"
        )


@router.post(
    "/final-summary",
    response_model=FinalSummaryApiResponse,
    summary="最终汇总 - 生成综合检测结果",
    description="完成所有分步检测后，生成最终的综合检测结果并保存到数据库"
)
async def final_summary(
    request: FinalSummaryRequest,
    current_user: User = Depends(get_current_user)
):
    """最终汇总 - 生成综合检测结果"""
    try:
        # 创建检测服务实例
        detection_service = DetectionService()
        
        result = await detection_service.final_summary(
            user_id=current_user.id,
            session_id=request.session_id
        )
        
        # 判断检测结果是否完整
        detection_result = result.result
        is_complete_result = (
            detection_result.basp_type not in ["未知", "错误", "无法识别", ""] and
            detection_result.severity not in ["未知", "错误", "无法识别", ""] and
            detection_result.description not in ["检测完成", "检测失败", "错误", "无法识别", ""] and
            detection_result.suggestion not in ["请咨询专业医生", "检测失败", "错误", "无法识别", ""]
        )
        
        return SuccessResponse(
            data=result,
            message="检测汇总完成",
            success=is_complete_result
        )
        
    except Exception as e:
        error_msg = str(e)
        logger.error(f"最终汇总失败: {error_msg}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"最终汇总失败: {error_msg}"
        )


@router.get(
    "/session/{session_id}/status",
    response_model=SuccessResponse[dict],
    summary="获取检测会话状态",
    description="查询指定会话的检测进度和状态"
)
async def get_session_status(
    session_id: str,
    current_user: User = Depends(get_current_user)
):
    """获取检测会话状态"""
    try:
        # 创建检测服务实例
        detection_service = DetectionService()
        
        status_info = await detection_service.get_session_status(session_id)
        
        if not status_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="会话不存在或已过期"
            )
        
        # 验证用户权限
        if status_info['user_id'] != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权访问此检测会话"
            )
        
        return SuccessResponse(
            data=status_info,
            message="获取会话状态成功"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        error_msg = str(e)
        logger.error(f"获取会话状态失败: {error_msg}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取会话状态失败: {error_msg}"
        )